import java.io.*;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;

@ContextConfiguration(locations = {"classpath:test-xsl-beans.xml"})
public class XslTransformerTestCase extends AbstractTestNGSpringContextTests {
    private static final String sourceName = "emku";

    private static final String ROOT_BEGIN = "<files>";
    private static final String ROOT_END = "</files>";

    private static final String DOC_FILENAME = "<doc filename=\"%s\"/>";

    private static final String xslFilePath = String.format("/%s_volatile_assemble.xslt", sourceName);

    private static final String listFilesPath = String.format("C://temp//%s//files.xml", sourceName);
    private static final String dataFolderPath = String.format("C://temp//%s//data", sourceName);
    private static final String outputFilePath = String.format("C://temp//%s//out//out.xml", sourceName);

    @Test(groups = "assemble")
    public void assemble() throws TransformerFactoryConfigurationError, TransformerException, IOException {
        InputStream xslStream = this.getClass().getResourceAsStream(xslFilePath);
        InputStream listFilesStream = new FileInputStream(listFilesPath);
        ByteArrayOutputStream resXMLOutput = new ByteArrayOutputStream();
        Result resXML = new StreamResult(resXMLOutput);

        Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xslStream));
        transformer.transform(new StreamSource(listFilesStream), resXML);
        FileOutputStream fo = new FileOutputStream(outputFilePath);
        fo.write(resXMLOutput.toByteArray());
        fo.flush();
        fo.close();
    }

    @Test(groups = "generate")
    public void generateListFiles() throws IOException {
        File folder = new File(dataFolderPath);
        if (folder.isDirectory()){
            StringBuilder sb = new StringBuilder();
            sb.append(ROOT_BEGIN);
            File[] listFiles = folder.listFiles();
            for (File file : listFiles){
                String name = String.format("%s//%s", dataFolderPath, file.getName());
                sb.append(String.format(DOC_FILENAME, name));
            }
            sb.append(ROOT_END);
            FileWriter fw = new FileWriter(listFilesPath);
            fw.write(sb.toString());
            fw.close();
        }
    }

}
